import React, { useReducer } from 'react'
import { createContainer } from '@kedacom/hooks'
import { BoxInfoProps, IAction, TVWallConfigProps } from './interface'
import { FetchTVWallItem } from '@/api/sysConfig/tvWallConfig/interface'
import { transTVWallEditInfo } from './translator'

function reducer(state: TVWallConfigProps, action: IAction) {
	switch (action.type) {
		case 'update':
			return { ...action.payLoad }
		case 'changeApplyState':
			return { ...state, isApply: action.payLoad }
		case 'changeTVWallName':
			return { ...state, name: action.payLoad }
		case 'changeColumnNum':
			return { ...state, columnNum: action.payLoad }
		case 'changeLineNum':
			return { ...state, lineNum: action.payLoad }
		case 'deleteTVwall':
			return {
				...state,
				boxList: state.boxList.filter((item, index) => {
					return index !== action.payLoad
				}),
			}
		case 'changeBoxList':
			return { ...state, boxList: [...action.payLoad] }
		case 'changeBoxListParams':
			let paramsInfo = action.payLoad
			let newList = state.boxList.map((item: BoxInfoProps, index: number) => {
				if (index === paramsInfo.boxIndex) {
					return { ...item, ...paramsInfo.configObj }
				} else {
					return item
				}
			})
			return { ...state, boxList: newList }
		default:
			return state
	}
}

const TVWallContainer = createContainer((value: FetchTVWallItem | undefined) => {
	const initState: TVWallConfigProps = transTVWallEditInfo(value)
	const [state, dispatch] = useReducer(reducer, initState)

	return {
		state,
		dispatch,
	}
})
export default TVWallContainer
